<template>
  <a-form ref="formRef" class="login-form" :model="loginForm" :rules="rules">
    <a-form-item name="username">
      <a-input v-model:value.trim="loginForm.username" placeholder="请输入用户名" />
    </a-form-item>
    <a-form-item name="password">
      <a-input-password v-model:value="loginForm.password" autocomplete="on" :type="showPassword ? 'text' : 'password'" placeholder="请输入密码：至少三种字符，最小 8 位" />
    </a-form-item>
    <a-form-item name="captcha">
      <a-input class="captcha-input" v-model:value.trim="loginForm.captcha" placeholder="请输入验证码" />
      <a-image width="40%" style="cursor: pointer" :preview="false" :src="captchaBase64Image" @click="getCaptcha" />
    </a-form-item>
    <a-form-item>
      <a-checkbox v-model:checked="rememberPwd">记住密码</a-checkbox>
    </a-form-item>
    <a-form-item>
      <a-button class="btn" type="primary" html-type="submit" @click="onLogin">登录</a-button>
    </a-form-item>
  </a-form>
</template>
<script setup lang="ts">
import { message } from 'ant-design-vue'
import { useUserStore } from '@/store/modules/user-store'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
import { useStorage } from '@/hooks/web/use-storage-hook'
import { LocalStorageKeyConst } from '@/constants/framework/local-storage-key-const'
import { loginApi } from '@/api/system/login-api'
import eventEmitter from '@/lib/event-emitter'
const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
  keep_login: '1'
})
const rules = {
  username: [{ required: true, message: '用户名不能为空' }],
  password: [{ required: true, message: '密码不能为空' }],
  captcha: [{ required: true, message: '验证码不能为空' }]
}
const showPassword = ref(false)
const router = useRouter()
const formRef = ref()
const rememberPwd = ref(false)
const { setStorage } = useStorage()
const { setUserLoginInfo } = useUserStore()
const Loading = useLoadingStore()

//登录
function onLogin() {
  formRef.value.validate().then(async () => {
    try {
      Loading.show()
      await loginApi.logout()
      const initInfo = await loginApi.login(loginForm)
      const menuInfo = await loginApi.getLoginInfo()
      const userInfo = {
        menuInfo,
        ...initInfo.data.user
      }
      // 更新用户信息到pinia
      setUserLoginInfo(userInfo)
      stopRefreshCaptchaInterval()
      setStorage(LocalStorageKeyConst.USER_TOKEN, 'token')
      message.success('登录成功')

      // 构建系统的路由
      eventEmitter.emit('Router:reload', menuInfo)
      router.replace('/')
    } catch (e: any) {
      if (e.code !== 200) {
        message.error(e.msg)
        loginForm.captcha = ''
        getCaptcha()
      }
      errorSentry.captureError(e)
    } finally {
      Loading.hide()
    }
  })
}

//--------------------- 验证码 ---------------------------------

const captchaBase64Image = ref('')
async function getCaptcha() {
  try {
    let captchaResult = await loginApi.getCaptcha()
    captchaBase64Image.value = URL.createObjectURL(new Blob([captchaResult.data]))
    // loginForm.captchaUuid = captchaResult.data.captchaUuid;
    // beginRefreshCaptchaInterval(captchaResult.data.expireSeconds);
  } catch (e) {
    console.log(e)
  }
}

let refreshCaptchaInterval = null
function beginRefreshCaptchaInterval(expireSeconds) {
  if (refreshCaptchaInterval === null) {
    refreshCaptchaInterval = setInterval(getCaptcha, (expireSeconds - 5) * 1000)
  }
}

function stopRefreshCaptchaInterval() {
  if (refreshCaptchaInterval != null) {
    clearInterval(refreshCaptchaInterval)
    refreshCaptchaInterval = null
  }
}

onMounted(getCaptcha)
</script>
<style scoped lang="less">
.login-form {
  .captcha-input {
    width: 60%;
  }

  .captcha-img {
    cursor: pointer;
  }
}
.ant-input,
.ant-input-affix-wrapper {
  height: 44px;
  border: 1px solid #ededed;
  border-radius: 4px;
}

.code-btn {
  height: 44px;
  padding: 4px 5px;
  width: 108px;
}

.eye-box {
  position: absolute;
  right: 15px;
  top: 10px;
  .eye-icon {
    width: 20px;
    height: 20px;
    cursor: pointer;
  }
}
.btn {
  width: 350px;
  height: 50px;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 700;
}
.captcha-input {
  width: 60%;
}

.captcha-img {
  width: 40%;
  cursor: pointer;
}
</style>
